const mongoose = require('mongoose')
//连接数据库
mongoose.connect('mongodb://localhost/xia')
.then(() => {
    console.log("连接成功了")
})
.catch(err => {
    console.log(err)
})
//创建规则
const PostSchema = new mongoose.Schema({
    title: {
        type: String,
        required: [true, '请传入标题'],
        minlength: 2,
        maxlength: 5,
        trim: true,
    },
    age: {
        type: Number,
        min: 2,
        max: [100, '不能超过最大年龄100岁']
    },
    publishDate: {
        type: Date,
        default: Date.now
    },
    category: {
        type: String,
        enum: {
            values: ['上刊', '自有', '下刊'],
            message: '请正确写入拍照种类'
        }
    },
    author: {
        type: String,
        validate: {
            validator: value => {
                return value && value.length >= 2
            },
            message: '作者名长度不能小于2'
                }
        }

})

const Validata = mongoose.model('Validata', PostSchema)
Validata.create({title:'验证测试',age: 28,
                 category:'上刊拍照', author: '夏'})
.then(res => {
    console.log(res)
})
.catch(err => {
    console.log(err.errors)
    /**
     * err.errors错误对象格式
     * {{属性1:properties},
     * {属性2:properties}}
     * 
     * properties为对象,
     * message属性指向错误原因
     * 
    */ 

    // 遍历错误对象属性
    console.log(Object.keys(err.errors).forEach(item => {
        //    获取错误信息
         console.log(err.errors[item].properties.message)
    }))
})